package org.wx.io.nio;

import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * NIO 文件处理 != 1 ->
 * @author wangxun
 * @version 1.0
 * @description: TODO
 * @date 2021/1/29 3:35 下午
 */
public class FileNIOTest {

    final Logger logger = LoggerFactory.getLogger(getClass());
    @Test
    void Test() throws IOException {
        File file = new File("src/main/resources/I.txt");
        logger.info(file.getPath());
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
        FileChannel channel = randomAccessFile.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(4096);

        byteBuffer.put("ab".getBytes());
        // 将ByteBuffer写模式调整到读模式
        channel.write((ByteBuffer) byteBuffer.flip());

        // 调用文件描述符 同步
        randomAccessFile.close();

        channel = new RandomAccessFile(file, "rw").getChannel();

        byteBuffer.compact();

        channel.read(byteBuffer);
        logger.info(new String(byteBuffer.array()));
        randomAccessFile.close();

    }

    @Test
    void Test2() throws IOException {
        File file = new File("src/main/resources/I.txt");
        logger.info(file.getPath());
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
        FileChannel channel = randomAccessFile.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(4096);

        channel.read(byteBuffer);
        logger.info(new String(byteBuffer.array()));
        randomAccessFile.close();

    }

    /**
     * transferFrom
     * transferTo
     */
    @Test
    void transferTest() throws IOException {
        FileInputStream in = new FileInputStream("src/main/resources/I.txt");
        FileOutputStream out = new FileOutputStream("src/main/resources/out.txt");
        FileChannel src = in.getChannel();
        FileChannel dest = out.getChannel();

        dest.transferFrom(src,0,src.size());

        in.close();
        out.close();
    }
}
